﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace AMing.Mvc4.Core.Method
{
    public class TextFile
    {
        /// <summary>
        /// 读取txt文本内容
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static string TxtFileRead(string filepath)
        {
            System.IO.FileInfo fileInfo = new FileInfo(filepath);
            if (fileInfo.Exists)
            {
                using (var stream = fileInfo.Open(System.IO.FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 保存Txt文件
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="txt"></param>
        public static void TxtFileWrite(string filepath, string txt)
        {
            string folder = System.IO.Path.GetDirectoryName(filepath);

            System.IO.DirectoryInfo dirInfo = new DirectoryInfo(folder);
            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }
            System.IO.FileInfo fileInfo = new FileInfo(filepath);

            using (var stream = fileInfo.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamWriter sw = new StreamWriter(stream))
                {
                    sw.Write(txt);
                }
            }
        }
    }
}
